// common/passport
import passport from "passport";
import passportJWT from "passport-jwt";
import UserService from "../api/users/user.service.js";
import ROLE from "../api/users/role.model.js";

const JwtStrategy = passportJWT.Strategy;
const ExtractJwt = passportJWT.ExtractJwt;
const opts = {};
opts.jwtFromRequest = ExtractJwt.fromAuthHeaderAsBearerToken();
opts.secretOrKey = process.env.JWT_SECRET;

// Regular JWT authentication strategy
passport.use(
  "jwt",
  new JwtStrategy(opts, async (jwtPayload, done) => {
    const user = await UserService.oneBy({ email: jwtPayload.user.email });
    return done(null, user);
  })
);

// Super Admin JWT authentication strategy
passport.use(
  "super-jwt", 
  new JwtStrategy(opts, async (jwtPayload, done) => {
    try {
      const user = await UserService.oneBy({ email: jwtPayload.user.email });
      
      // If user doesn't exist or isn't a Super Admin, deny access
      if (!user || user.role !== ROLE.SUPER_ADMIN) {
        return done(null, false, { message: 'Only Super Admins can access this resource' });
      }
      
      return done(null, user);
    } catch (error) {
      return done(error, false);
    }
  })
);

// Helper middleware function for Super Admin authentication
export const authenticateSuper = () => {
  return passport.authenticate("super-jwt", { session: false });
};

// NEW: Helper middleware function for both regular and Super Admin authentication
export const authenticateUsers = () => {
  return (req, res, next) => {
    // First try to authenticate with super-jwt
    passport.authenticate("super-jwt", { session: false }, (err, user, info) => {
      if (err) {
        return next(err);
      }
      
      // If super-jwt authentication succeeds
      if (user) {
        req.user = user;
        return next();
      }
      
      // If super-jwt fails, try regular jwt
      passport.authenticate("jwt", { session: false }, (err, user, info) => {
        if (err) {
          return next(err);
        }
        
        // If regular jwt authentication succeeds
        if (user) {
          req.user = user;
          return next();
        }
        
        // If both authentications fail, return unauthorized
        return res.status(401).json({ message: "Unauthorized" });
      })(req, res, next);
    })(req, res, next);
  };
};